import web, datetime
import json, time
import subprocess 

import os
import os.path, time

import logging
import logging.handlers
import glob

my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address = '/dev/log')
my_logger.addHandler(handler)

class Package:
    logfile = "/www/pages/operate/opkg_install.log"
    
    @staticmethod
    def list_upgradable():
        packages = []
        try:
            ret = subprocess.check_output(["opkg", "list-upgradable"])        
            for line in ret.split("\n"):
                if " - " in line:
                    [name, cur, next] = line.split(" - ")
                    packages.append({"name": name, 
                        "version": cur, 
                        "next": next})
        except OSError as e:
            return (False, str(e))
        except subprocess.CalledProcessError as e:
            return (False, str(e))
        return (True, packages)


    @staticmethod 
    def update_feed():
        args = ["opkg","update"]
        try:
            return True if subprocess.call(args) == 0 else False
        except OSError:
            return False

    @staticmethod
    def install_selected(selected):
        args = ["opkg", "install"]
        args.extend(selected)
        try:
            with open(Package.logfile, "w+") as log:
                popen = subprocess.Popen(args, stdout=log)
                ret_code = popen.wait()
                log.flush()
        except IOError as e:
            return (False, str(e))
        return (True, ret_code)

    @staticmethod 
    def get_install_log():
        if os.path.isfile(Package.logfile):
            with open(Package.logfile) as f:
                return f.read()
        return "Missing log file :("
    @staticmethod
    def last_updated():
        ''' Get the timestamp of the last updated file '''
        dir = "/var/lib/opkg/lists/"
        newest = max(glob.iglob(dir+"*"), key=os.path.getctime)
        return time.ctime(os.path.getmtime(newest))

    @staticmethod
    def info(name):
        try:
            ret = subprocess.check_output(["opkg", "info", name])
            return ret
        except OSError:
            pass
        return "Package info error"

    def __init__(self, name):
        self.name = name
    
    def get_version(self):
        args = ("opkg list-installed "+self.name).split()
        
        try:
            line = subprocess.check_output(args)
            return line.split(" - ")[1]
        except OSError:
            return "Unknown"
        
    def get_new_version(self):
        args = ("opkg list-upgradable").split()
        
        try:
            ret = subprocess.check_output(args)        
            for line in ret.split("\n"):             
                if self.name in line: 
                    return line.split(" - ")[2]
            return "Unknown"
        except OSError:
            return "Unknown"

    def is_upgradable(self):
        args = ("opkg list-upgradable").split()
        
        try:
            ret = subprocess.check_output(args)        
            for line in ret.split("\n"):             
                if self.name in line: 
                    return True
            return False
        except OSError:
            return False

    def upgrade(self):
        args = ["opkg", "install", self.name]
        
        try:
            return True if subprocess.call(args) == 0 else False
        except OSError:
            return False

